export default class SocketService{
    static instance=null
    static get Instance(){
        if(!this.instance){
            this.instance=new SocketService()
        }
        return this.instance
    }

    ws=null
    connected=false
    tryConnecting=true
    sendRetryCount=0
    connectRetryCount=0
    //设置最大连接次数
    limitTimes=6
    callBackMapping={}

    connect(){
        this.ws=new WebSocket('ws://127.0.0.1:9998')

        this.ws.onopen = () => {
            console.log('connect success!')
            this.connected=true
            this.connectRetryCount=0
        }

        this.ws.onclose = () => {
            console.log('connect error!')
            this.connected=false
            this.connectRetryCount++
            if (this.connectRetryCount > this.limitTimes) {
                this.connectRetryCount = 0
                this.tryConnecting=false
               alert('连接超时,请刷新')
                return
            }
            setTimeout(()=>{
                this.connect()
            },500*this.connectRetryCount)
        }

        this.ws.onmessage=msg=>{
            const data=JSON.parse(msg.data)
            const socketType=data.socketType
            if(this.callBackMapping[socketType]){
                const action=data.action
                if(action==='getData'){
                    const realData=JSON.parse(data.data)
                    this.callBackMapping[socketType].call(this,realData)
                }
                else if(action==='fullScreen'){

                }
                else if(action==='themeChange'){

                }
            }
            else this.registerCallBack(socketType)
        }
    }

    registerCallBack(socketType,callback){
        this.callBackMapping[socketType]=callback
    }
    unRegisterCallBack(socketType){
        delete this.callBackMapping[socketType]
    }

    send(data){
        if(this.connected){
            this.ws.send(JSON.stringify(data))
            this.sendRetryCount=0
        }
        else{
            this.sendRetryCount++
            if(!this.tryConnecting){
                this.sendRetryCount=0
                this.tryConnecting=true
                alert('发送请求超时，请刷新')
                return
            }
            setTimeout(()=>{
                this.send(data)
            },this.sendRetryCount*500)
        }
    }
}